/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package org.ipo.mm.web.actions;

import java.util.List;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.naming.Context;
import javax.naming.InitialContext;
import javax.naming.NamingException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionForward;
import org.apache.struts.action.ActionMapping;
import org.ipo.mm.ejb.entities.City;
import org.ipo.mm.ejb.entities.InstitutionFamily;
import org.ipo.mm.ejb.entities.InstitutionRegion;
import org.ipo.mm.ejb.entities.InstitutionType;
import org.ipo.mm.ejb.facade.city.CityFacadeLocal;
import org.ipo.mm.ejb.facade.family.InstitutionFamilyFacadeLocal;
import org.ipo.mm.ejb.facade.region.InstitutionRegionFacadeLocal;
import org.ipo.mm.ejb.facade.type.InstitutionTypeFacadeLocal;
import org.ipo.mm.web.formbeans.InstitutionSearchBean;
import org.ipo.mm.web.util.BreadCrumbs;
import org.ipo.mm.web.util.ConstantManager;
import org.ipo.mm.web.util.pager.AbstractPager;
import org.ipo.mm.web.util.pager.InstitutionPager;

/**
 *
 * @author makcro
 */
public class InstitutionSearchAction extends org.apache.struts.action.Action {

    @Override
    public ActionForward execute(ActionMapping mapping, ActionForm form,
            HttpServletRequest request, HttpServletResponse response)
            throws Exception {

        ActionForward actionForward = null;
        injectAdvSearchBaseData(request);

        String pageNumber = request.getParameter("p");

        BreadCrumbs bc = (BreadCrumbs) request.getSession().getAttribute(ConstantManager.SESSION_BREADCRUMB_PARAM_NAME);
        String bcName = (pageNumber == null) ? ConstantManager.BC_INST_LIST : ConstantManager.BC_INST_LIST + "-" + pageNumber;
        bc.push(bcName, request);

        AbstractPager pager = null;
        

        // declare search vars
        String nameFilter = null;
        String nameFilterOperator = null;

        String addressFilter = null;
        String addressOperator = null;

        String faxFilter = null;
        String faxOperator = null;

        String emailFilter = null;
        String emailOperator = null;

        String telephoneFilter = null;
        String telephoneOperator = null;

        String representativeFlter = null;
        String representativeOperator = null;

        String[] typeFilter = null;
        String[] regionFilter = null;
        String[] familyFilter = null;
        String[] cityFilter = null;

        String orderBy = null;

        //if this is true then user submited search or opend this page for the first time
        //anyway pager is created
        if (pageNumber == null) {

            // first chech if any quic links are used
            String familyId = request.getParameter("fid");
            String typeId = request.getParameter("tid");
            String regionId = request.getParameter("rid");
            String cityId = request.getParameter("cid");
            String orderByParam = request.getParameter("orderBy");
            // find by family
            if (familyId != null) {
                familyFilter = new String[]{familyId};
            } // find by type
            else if (typeId != null) {
                typeFilter = new String[]{typeId};
            } // find by region
            else if (regionId != null) {
                regionFilter = new String[]{regionId};
            } // find by city
            else if(cityId != null){
                cityFilter = new String[]{cityId};
            }

            else if(orderByParam != null){
                orderBy = orderByParam;
            }
            // find using advanced search form data
            else {
                InstitutionSearchBean isb = (InstitutionSearchBean) form;

                nameFilter = (isb.getNameFilter() == null || "".equals(isb.getNameFilter().trim()) ? null : isb.getNameFilter().trim());
                nameFilterOperator = isb.getNameOperator();

                addressFilter = (isb.getFaxFilter() == null || "".equals(isb.getFaxFilter().trim()) ? null : isb.getFaxFilter().trim());
                addressOperator = isb.getAddressOperator();

                faxFilter = (isb.getFaxFilter() == null || "".equals(isb.getFaxFilter().trim()) ? null : isb.getFaxFilter().trim());
                faxOperator = isb.getFaxOperator();

                emailFilter = (isb.getEmailFilter() == null || "".equals(isb.getEmailFilter().trim()) ? null : isb.getEmailFilter().trim());
                emailOperator = isb.getEmailOperator();

                telephoneFilter = (isb.getTelephoneFilter() == null || "".equals(isb.getTelephoneFilter().trim()) ? null : isb.getTelephoneFilter().trim());
                telephoneOperator = isb.getTelephoneOperator();

                representativeFlter = (isb.getRepresentativeFilter() == null || "".equals(isb.getRepresentativeFilter().trim()) ? null : isb.getRepresentativeFilter().trim());
                representativeOperator = isb.getRepresentativeOperator();

                typeFilter = isb.getTypeFilter();
                regionFilter = isb.getRegionFilter();
                familyFilter = isb.getFamilyFilter();
                cityFilter = isb.getCityFilter();

                orderBy = isb.getOrderBy() == null || "".equals(isb.getOrderBy().trim()) ? "name" : isb.getOrderBy().trim();
            }


            

            pager = new InstitutionPager(nameFilter,
                    nameFilterOperator,
                    addressFilter,
                    addressOperator,
                    emailFilter,
                    emailOperator,
                    telephoneFilter,
                    telephoneOperator,
                    faxFilter,
                    faxOperator,
                    representativeFlter,
                    representativeOperator,
                    typeFilter,
                    regionFilter,
                    familyFilter,
                    cityFilter,
                    orderBy);

            request.getSession().setAttribute(ConstantManager.SESSION_INST_PAGER, pager);



        } else {

            pager = (AbstractPager) request.getSession().getAttribute(ConstantManager.SESSION_INST_PAGER);
            pager.setPageNumber(Integer.parseInt(pageNumber));


        }

        pager.doPaging(request);

        actionForward = mapping.findForward(ConstantManager.NAVIGATION_INSTITUTION_LIST);







        return actionForward;
    }

    private void injectAdvSearchBaseData(HttpServletRequest request) {


        List<InstitutionRegion> regions = lookupInstitutionRegionFacade().findAll();
        List<InstitutionType> types = lookupInstitutionTypeFacade().findAll();
        List<InstitutionFamily> families = lookupInstitutionFamilyFacade().findAll();
        List<City> cities = lookupCityFacade().findAll();

        request.setAttribute("search_regions", regions);
        request.setAttribute("search_types", types);
        request.setAttribute("search_families", families);
        request.setAttribute("search_cities", cities);

    }

    private InstitutionTypeFacadeLocal lookupInstitutionTypeFacade() {
        try {
            Context c = new InitialContext();
            return (InstitutionTypeFacadeLocal) c.lookup("java:comp/env/InstitutionTypeFacade");
        } catch (NamingException ne) {
            Logger.getLogger(getClass().getName()).log(Level.SEVERE, "exception caught", ne);
            throw new RuntimeException(ne);
        }
    }

    private InstitutionRegionFacadeLocal lookupInstitutionRegionFacade() {
        try {
            Context c = new InitialContext();
            return (InstitutionRegionFacadeLocal) c.lookup("java:comp/env/InstitutionRegionFacade");
        } catch (NamingException ne) {
            Logger.getLogger(getClass().getName()).log(Level.SEVERE, "exception caught", ne);
            throw new RuntimeException(ne);
        }
    }

    private InstitutionFamilyFacadeLocal lookupInstitutionFamilyFacade() {
        try {
            Context c = new InitialContext();
            return (InstitutionFamilyFacadeLocal) c.lookup("java:comp/env/InstitutionFamilyFacade");
        } catch (NamingException ne) {
            Logger.getLogger(getClass().getName()).log(Level.SEVERE, "exception caught", ne);
            throw new RuntimeException(ne);
        }
    }

    private CityFacadeLocal lookupCityFacade() {
        try {
            Context c = new InitialContext();
            return (CityFacadeLocal) c.lookup("java:comp/env/CityFacade");
        } catch (NamingException ne) {
            Logger.getLogger(getClass().getName()).log(Level.SEVERE, "exception caught", ne);
            throw new RuntimeException(ne);
        }
    }
}
